package com.ruoyi.jiaopei.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.jiaopei.domain.TbStudent;
import com.ruoyi.jiaopei.domain.bo.TbStudentBo;
import com.ruoyi.jiaopei.domain.vo.StudentCurriculumVo;
import com.ruoyi.jiaopei.domain.vo.TbStudentVo;
import com.ruoyi.jiaopei.mapper.TbCurriculumMapper;
import com.ruoyi.jiaopei.mapper.TbStudentMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.jiaopei.domain.bo.TbRecordBo;
import com.ruoyi.jiaopei.domain.vo.TbRecordVo;
import com.ruoyi.jiaopei.domain.TbRecord;
import com.ruoyi.jiaopei.mapper.TbRecordMapper;
import com.ruoyi.jiaopei.service.ITbRecordService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 核销记录Service业务层处理
 *
 * @author macy
 * @date 2024-04-11
 */
@RequiredArgsConstructor
@Service
public class TbRecordServiceImpl implements ITbRecordService {

    private final TbRecordMapper baseMapper;
    private final TbCurriculumMapper curriculumMapper;
    private final TbStudentMapper studentMapper;
    private final ISysUserService sysUserService;

    /**
     * 查询核销记录
     */
    @Override
    public TbRecordVo queryById(Long id){
        TbRecordVo recordVo=baseMapper.selectVoById(id);
        if(null!=recordVo){
            recordVo.setCurriculumVo(curriculumMapper.selectVoById(recordVo.getCurriculumId()));
            recordVo.setStudentVo(studentMapper.selectVoById(recordVo.getStudentId()));
            recordVo.setTeacherVo(sysUserService.selectUserById(recordVo.getTeacherId()));
        }
        return recordVo;
    }

    /**
     * 查询核销记录列表
     */
    @Override
    public TableDataInfo<TbRecordVo> queryPageList(TbRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbRecord> lqw = buildQueryWrapper(bo);
        Page<TbRecordVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询核销记录列表
     */
    @Override
    public List<TbRecordVo> queryList(TbRecordBo bo) {
        LambdaQueryWrapper<TbRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbRecord> buildQueryWrapper(TbRecordBo bo) {

        QueryWrapper<TbRecord> lqw1 = Wrappers.query();
        lqw1.like(StringUtils.isNotBlank(bo.getStudentName()),"s.name", bo.getStudentName());
        lqw1.like(StringUtils.isNotBlank(bo.getCurriculumName()),"c.name", bo.getCurriculumName());
        lqw1.like(StringUtils.isNotBlank(bo.getTeacherName()),"u.nick_name", bo.getTeacherName());
        lqw1.like(StringUtils.isNotBlank(bo.getStatus()),"t.status", bo.getStatus());


        LambdaQueryWrapper<TbRecord> lqw =lqw1.lambda();
        lqw.eq(bo.getStudentId() != null, TbRecord::getStudentId, bo.getStudentId());
        lqw.eq(bo.getCurriculumId() != null, TbRecord::getCurriculumId, bo.getCurriculumId());
        lqw.eq(StringUtils.isNotBlank(bo.getRelease()), TbRecord::getRelease, bo.getRelease());
        lqw.eq(StringUtils.isNotBlank(bo.getCourseDuration()), TbRecord::getCourseDuration, bo.getCourseDuration());
        lqw.eq(bo.getLessonHours() != null, TbRecord::getLessonHours, bo.getLessonHours());
        lqw.eq(StringUtils.isNotBlank(bo.getStartHour()), TbRecord::getStartHour, bo.getStartHour());
        lqw.eq(StringUtils.isNotBlank(bo.getEndHour()), TbRecord::getEndHour, bo.getEndHour());

        lqw.eq(StringUtils.isNotBlank(bo.getPhoto()), TbRecord::getPhoto, bo.getPhoto());
        lqw.eq(bo.getSignDate() != null, TbRecord::getSignDate, bo.getSignDate());
        lqw.eq(StringUtils.isNotBlank(bo.getEvaluate()), TbRecord::getEvaluate, bo.getEvaluate());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), TbRecord::getRemarks, bo.getRemarks());
        lqw.eq(bo.getCreatedDate() != null, TbRecord::getCreatedDate, bo.getCreatedDate());


        lqw.orderByDesc(TbRecord::getCreatedDate);

        return lqw;
    }

    /**
     * 新增核销记录
     */
    @Override
    public Boolean insertByBo(TbRecordBo bo) {
        TbRecord add = BeanUtil.toBean(bo, TbRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改核销记录
     */
    @Override
    public Boolean updateByBo(TbRecordBo bo) {
        TbRecord update = BeanUtil.toBean(bo, TbRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbRecord entity){
        if(null==entity.getId()){
            entity.setCreatedDate(new Date());

            if(null==entity.getTeacherId()){
                entity.setTeacherId(LoginHelper.getUserId());
            }

            if(StrUtil.isBlank(entity.getCourseDuration())){
                entity.setCourseDuration(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date()));
            }

            /**
             * 查找 学员 课时余额
             */

            QueryWrapper<TbStudent> lqw1 = Wrappers.query();
            lqw1.eq(null!=entity.getStudentId(),"a.student_id",entity.getStudentId());
            lqw1.eq(null!=entity.getCurriculumId(),"a.curriculum_id",entity.getCurriculumId());

            StudentCurriculumVo studentCurriculumVo=studentMapper.queryStudentCurriculumInfo(lqw1.lambda());
            if(null==studentCurriculumVo){
                throw new ServiceException("请先购买课时");
            }
            if(studentCurriculumVo.getSyHours().subtract(entity.getLessonHours()).doubleValue()<0){
                throw new ServiceException("课时不足，请先购买课时");
            }

        }
    }

    /**
     * 批量删除核销记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
